'use strict';
const db = uniCloud.database()
const dbCmd = db.command
const watchAdDBName = 'zhy_watch_ad'
const userQueueDBName = 'zhy_comsume_queue'

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	if (event.operateType == 'test') {
		// 测试
		await waitQueueRefreshFinished()
		return 0
	}

	let operateQueueType = event.operateQueueType
	if (operateQueueType == 1) {
		// 队列操作：1插队(随机插队1-5)
		/* data: {
			operateQueueType: 1, 
			user_id: uni.getStorageSync(app.globalData.session.userInfo).user_id,
			consume_id: that.consume_id,
		} */
		return await jumpQueue(event, context)
	} else if (operateQueueType == 2) {
		// 排队
		return await waitQueue(event, context)
	} else if (operateQueueType == 3) {
		// 离队
		return await leaveQueue(event, context)
	} else if (operateQueueType == 4) {
		// 退队
		return await breakQueue(event, context)
	}

	let otherType = event.otherType
	// 其他操作 otherType
	if (otherType == 1) {
		/* {
			otherType: 1, // 其他操作类型
			user_id: uni.getStorageSync(app.globalData.session.userInfo).user_id,
			consume_id: that.consume_id,
		}, */
		// 新增观看广告记录，并当日观看返回次数
		return await addWatchAdAndGetTimeByDay(event, context)
	}
	//返回数据给客户端
	console.log('参数类型不支持：' + operateQueueType);
	return false
};

// 插队：随机插队人数 1-5
async function jumpQueue(event, context) {

}

// 排队：队尾增加一个
async function waitQueue(event, context) {
	/*
	{
		business_id,user_id,order_time,
	}
	*/
	if (objIsEmpty(event.business_id) || objIsEmpty(event.user_id)) {
		// 根据consume_id查询business_id和user_id即可
		console.log('参数不齐');
		return false
	}
	// 判断是否正在修改表,并返回最大值：max_order_consume:只需要判断当前用户和商家--不需要和消费id挂钩
	let isUpdateUserQueue = await waitQueueRefreshFinished(event.user_id, event.business_id)
	// 即使前端超时，后台也会执行
	// Error: connect ETIMEDOUT 203.107.60.33:443, POST https://api.next.bspapp.com/server -1 
	// (connected: false, keepalive socket: false, socketHandledRequests: 1, socketHandledResponses: 0)
	if (isUpdateUserQueue == null) {
		console.log('等待队列更新超时，请重试');
		return false
	}
	// 对列表修改完毕:最大长度为isUpdateUserQueue.max_order_consume
	// 新增队列
	let addParam = {
		isDelete: 0,
		consume_order: isUpdateUserQueue.max_order_consume + 1,
		business_id: event.business_id,
		user_id: event.user_id,
		order_time: new Date().getTime()
	}
	await db.collection(userQueueDBName).add(addParam)
	return true
}

// 离队:队首离开（正常离开）
async function leaveQueue(event, context) {

}

// 退队：中途退出队列
async function breakQueue(event, context) {

}

// 新增观看广告记录，并当日观看返回次数
async function addWatchAdAndGetTimeByDay(event, context) {
	if (objIsEmpty(event) || objIsEmpty(event.user_id) || objIsEmpty(event.consume_id)) {
		console.log('参数不齐');
		return false
	}
	let addValue = {
		user_id: event.user_id,
		consume_id: event.consume_id,
		watch_time: new Date().getTime()
	}
	await db.collection(watchAdDBName).add(addValue)

	let result = {
		jumpQueueAble: false
	}
	// 查询次数
	let zeroTime = getZeroTimeStamp(new Date())
	let queryTimes = {
		user_id: event.user_id,
		watch_time: dbCmd.and(dbCmd.gte(zeroTime), dbCmd.lte(new Date().getTime()))
	}
	let res = await db.collection(watchAdDBName).where(queryTimes).count()
	if (res && res.total <= 3) {
		// 可以插队
		result.jumpQueueAble = true
	}
	return result
}

///=====================================非业务函数====================================//
function objIsEmpty(obj) {
	if (obj == undefined || obj == '' || obj == null || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}

// 获取date的0点时间戳：毫秒
function getZeroTimeStamp(date) {
	return new Date(date.toLocaleDateString()).getTime()
}

// 睡眠，单位毫秒
function sleep(delay) {
	return new Promise((resolve) => setTimeout(resolve, delay));
}

// 判断用户在某商家下排队
// 失败返回null,成功返回max_consume_order
async function waitQueueRefreshFinished(user_id, business_id) {
	/* if (objIsEmpty(user_id) || objIsEmpty(business_id)) {
		console.log('waitQueueRefreshFinished参数不齐');
		return null
	} */
	// 成功返回值
	let result = {
		max_order_consume: 0
	}
	let queryParam = {
		isDelete: 0,
		// user_id: user_id,
		// business_id: business_id,
		// user_id: '',
		business_id: 'bs1-K2HBiz',
	}
	let maxTimes = 200
	while (true) {
		if (maxTimes <= 0) {
			// 限制循环次数
			break
		}
		sleep(500)
		let maxResult = await db.collection(userQueueDBName).where(queryParam).orderBy('consume_order', 'desc')
			.limit(1).get();
		let totalResult = await db.collection(userQueueDBName).where(queryParam).count()
		let max = 0
		let total = totalResult.total
		if (maxResult == null || maxResult.data == null || maxResult.length == 0) {
			max = 0
		} else {
			let consume_order = maxResult.data[0]
			if (consume_order == null) {
				max = 0
			} else {
				max = consume_order
			}
		}
		if (max == total) {
			result.max_order_consume = max
			break
		} else {
			sleep(500)
		}
		maxTimes = maxTimes - 1
	}
	if (result.max_order_consume == 0) {
		// 等待超出限制
		return null
	}
	return result
}